package TagRate.project.client;

import TagRate.project.pages.client.Base;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.http.client.Request;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.History;
import com.google.gwt.user.client.ui.RootPanel;
import com.web_bloks.http.client.JSONCall;
import com.web_bloks.http.client.JSONCallback;
import com.web_bloks.system.client.Logger;
import com.web_bloks.url.client.Helper;
import com.web_bloks.api.client.User;

/**
 * 
 * @author Jean-Lou Dupont
 *
 */
public class Main implements EntryPoint, JSONCallback {

	protected User user = null;
	
	protected HistoryManager hm = null;
	protected Base base = null;

	public void onModuleLoad() {
		RootPanel rootPanel = RootPanel.get();
		
		//Create the base 'mainframe' panel where all content is displayed
		base = GWT.create(Base.class);
		rootPanel.add(base);

		// MessageManager
		MessageManager mm = GWT.create(MessageManager.class);
		mm.setLabel(base.getLabelHeaderMessage());
		
		// ContentManager
		ContentManager cm = GWT.create(ContentManager.class);
		cm.setBase(base);

		// PageManager
		PageManager pm = GWT.create(PageManager.class);
		cm.setPageManager(pm);
		
		// History Manager
		hm = GWT.create(HistoryManager.class);
		History.addHistoryListener(hm);
		hm.setContentManager(cm);
		
		//Fetch user parameters
		setupUserParameters();
		
		// Start!
		hm.navigateTo( Helper.extractFieldsFromLocation() );
	}

	public void onJSONCallError(Request request, Throwable exception) {
		Logger.logWarn(this.getClass()+".onJSONCallError: error fetching from /api/user");
	}

	public void onJSONCallResponseReceived(int code, JSONValue response) {
		
		user = User.fromJSON( response );
		
		base.setLoginLogoutUrls(user.getLoginUrl(), user.getLogoutUrl());
		base.setUserState( user.isLogged() );
		
		UserManager um = GWT.create(UserManager.class);
		
		um.setCurrentUser(user);
	}

	protected void setupUserParameters() {
		JSONCall jsc = GWT.create(JSONCall.class);
		jsc.setCallback(this);
		
		try {
			jsc.execute("/api/user/tagrate/Main.html/", null);
		} catch(Exception e) {
			Logger.logWarn(this.getClass()+".onModuleLoad: error performing /api/user/ call, msg="+e.getMessage());
		}
	}
}//END
